2024.4.4 Figureを用いた複数グラフのプロット【matplotlib】
code:p01.py
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
fig1 = plt.figure()
ax1 = fig1.add_subplot(211)
ax2 = fig1.add_subplot(212)
ax1.plot(x, y1)
ax2.plot(x, y2)
plt.show()
https://scrapbox.io/files/660e45c0a9a334002594657b.png
確認のために、オブジェクトの型を確認する。
code:p02.py
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
fig1 = plt.figure()
print(type(fig1))
ax1 = fig1.add_subplot(211)
ax2 = fig1.add_subplot(212)
print(type(ax1), type(ax2))
ax1.plot(x, y1)
ax2.plot(x, y2)
plt.show()
code:(結果).py
<class 'module'> # type(plt)
<class 'function'> # type(plt.figure)
<class 'matplotlib.figure.Figure'> # type(fig1)
<class 'method'> # type(fig1.method)
<class 'matplotlib.axes._axes.Axes'> <class 'matplotlib.axes._axes.Axes'> # type(ax1)
<class 'method'> # type(ax1.plot)
つまり、
1. モジュールplt(実体はmatplotlib.pyplot)のfigure関数を呼び出すと、Figure型インスタンスが生成される。これを変数fig1に割り当てる。
2. fig1のadd_subplotメソッドを呼び出すと、Axes型インスタンスが生成される。これを変数ax1, ax2に割り当てる。
3. ax1, ax2のplotメソッドを用いて、それぞれの領域内にグラフを描画する。
fig
├ ax1
└ ax2
参考:https://qiita.com/nkay/items/d1eb91e33b9d6469ef51